import { UUIDService } from './uuid.service';
import { UrlService } from './url.service';
import { HttpService } from './http.service';
import { Injectable } from '@nestjs/common';
import * as qiniu from 'qiniu';
import axios from 'axios';
import { IImageInfo } from '../image/image.entity';

/**
 * 负责把管理本项目的静态资源，全部传到七牛服务器上，和义务服务器分离
 */
@Injectable()
export class QiniuService {
    constructor(
        private http: HttpService,
        private urlService: UrlService,
        private uuidService: UUIDService,
    ) {}

    public qiniuConfig = {
        access_key: 'chJWNjyv2kKJrDO3lk3MiGsOQ28dKDTQq6V7DJLv',
        secret_key: '6TsoVLgTxs-xjLPn131PRLJJJoYfjUDpzO6hyxU-',
        scope: 'static',
        cdn_url: 'https://static.goushubao.com',
    };

    private mac = new qiniu.auth.digest.Mac(
        this.qiniuConfig.access_key,
        this.qiniuConfig.secret_key,
    );

    /**
     * 这个src是否为本七牛资源，如果不是可能需要替换
     */
    isImgSrcInQiniu(src: string): boolean {
        return src.includes(this.qiniuConfig.cdn_url);
    }

    /**
     * 获取src
     */
    async qiniuImageInfo(src: string): Promise<IImageInfo> {
        let info = await this.http.get(`${src}?imageInfo`);
        return {
            ...info,
            src,
        };
    }

    // 七牛上传凭证
    genToken(): string {
        const putPolicy = new qiniu.rs.PutPolicy({
            scope: this.qiniuConfig.scope,
            expires: 3600 * 24,
        });
        return putPolicy.uploadToken(this.mac);
    }

    /**
     * @param data Buffer类型
     * @param key 表示最终生成的url的链接，最终链接为 domain + key
     */
    qiniuUploadData(data: Buffer, key?: string): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            let extra = new qiniu.form_up.PutExtra();
            new qiniu.form_up.FormUploader().put(
                this.genToken(),
                key,
                data,
                extra,
                (err, ret) => {
                    if (err) {
                        return reject(err);
                    }
                    resolve(`${this.qiniuConfig.cdn_url}/${ret.key}`);
                },
            );
        });
    }

    // 把一个http图片上传到七牛
    async qiniuUploadHttpFile(httpUrl: string): Promise<string> {
        let data: Buffer = await axios
            .get(httpUrl, {
                responseType: 'arraybuffer',
            })
            .then(res => res.data);
        let ext = this.urlService.fileExtensionFromUrl(httpUrl);
        let key = this.uuidService.uuid();
        if (ext) {
            key = `${key}.${ext}`;
        }
        return await this.qiniuUploadData(data, key);
    }

    // 把一个http图片上传到七牛并获取详细信息
    async getInfoByHttpSrc(httpUrl: string) {
        let src = await this.qiniuUploadHttpFile(httpUrl);
        return await this.qiniuImageInfo(src);
    }
}
